#!/usr/bin/python
##John Talbot
## This script will divide the original line file into peices, one for each core
## specified in its terminal call

##The syntax for the call is python fileMaker.py <original file> <number of cores> <output directory>
import sys

def file_len(fname):
    with open(fname) as f:
        for i, l in enumerate(f):
            pass
    return i + 1

def writeIt(lineList,fileName,startPoint,endPoint):
    outfile=open(fileName, 'w')
    print "Writing out new point file: ", fileName
    for i in range(startPoint,endPoint+1):
        print i
        outfile.write(lineList[i])
    
    


def main():
    if len(sys.argv)==4:
        print "Splitting into: ", sys.argv[2], " files."
        print "NUMBER OF LINES: "
        numLines= file_len(sys.argv[1])
        print numLines
        print "Segmenting into ", sys.argv[2], "files with a predicted"
        segmentAmt= numLines/int(sys.argv[2])
        print segmentAmt, " number of lines per file"
        print 
        rawFile= open(sys.argv[1])
        outDir=sys.argv[3]
        

        lineList=[]
        for i in rawFile:
            lineList.append(i)
        for j in range (int(sys.argv[2])):
            if (j+1 != int(sys.argv[2])):
                print "Writing to ", j
                writeIt(lineList,outDir+"segment_"+str(j),j*segmentAmt,(j*segmentAmt)+segmentAmt-1)
            else: 
                print"Doing Last"
                writeIt(lineList,outDir+"segment_"+str(j),j*segmentAmt,numLines-1)
           
            
    else: 
        print "ERROR: PROVIDE <filename> <number of cores> <output directory>"
main()
